#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OpenHarmony跨平台编译助手 v1.2
功能特性：
1. 自动识别操作系统类型
2. 环境依赖智能检测与安装
3. 编译参数动态适配
4. 多线程加速编译
5. 异常捕获与日志追踪
"""

import os
import sys
import platform
import subprocess
import argparse
from datetime import datetime
from pathlib import Path

class OpenHarmonyBuilder:
    def __init__(self, config):
        self.os_type = platform.system()
        self.script_path = Path(__file__).parent.resolve()
        self.config = {
            'product': 'rk3568',  # 默认编译产品
            'target_arch': 'arm64',
            'jobs': os.cpu_count() * 2,
            **config
        }
        self._init_logger()

    def _init_logger(self):
        """初始化日志系统[1,3](@ref)"""
        log_dir = self.script_path / 'logs'
        log_dir.mkdir(exist_ok=True)
        self.log_file = log_dir / f"build_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
        
    def _execute_cmd(self, cmd, cwd=None):
        """跨平台命令执行封装"""
        try:
            proc = subprocess.run(
                cmd,
                cwd=cwd or self.script_path,
                shell=True,
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True
            )
            with open(self.log_file, 'a') as f:
                f.write(f"\nCMD: {' '.join(cmd)}\n")
                f.write(proc.stdout)
            return True
        except subprocess.CalledProcessError as e:
            print(f"命令执行失败: {e.output}")
            return False

    def check_dependencies(self):
        """环境依赖检测与安装[1,2,3](@ref)"""
        deps = {
            'Linux': ['git', 'make', 'gcc', 'python3', 'qemu-system-x86'],
            'Windows': ['git', 'python.exe', 'Hyper-V']
        }
        
        current_os_deps = deps.get(self.os_type, [])
        print(f"正在检测{self.os_type}环境依赖...")
        
        # Windows环境检测Hyper-V[1](@ref)
        if self.os_type == 'Windows':
            hv_status = subprocess.check_output(
                'dism.exe /online /Get-FeatureInfo /FeatureName:Microsoft-Hyper-V-All',
                shell=True
            )
            if b'Enabled' not in hv_status:
                print("启用Hyper-V：")
                self._execute_cmd(
                    'powershell "Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All -NoRestart"'
                )

        # Linux环境检测软件包[3](@ref)
        elif self.os_type == 'Linux':
            for pkg in current_os_deps:
                if not Path(f"/usr/bin/{pkg}").exists():
                    self._execute_cmd(['sudo', 'apt-get', 'install', '-y', pkg])

    def setup_repo(self):
        """配置源码仓库[3](@ref)"""
        repo_url = "https://gitee.com/openharmony/manifest.git"
        branch = "OpenHarmony-4.1-Beta1"
        
        # 初始化repo工具
        if not (self.script_path / '.repo').exists():
            print("初始化repo仓库...")
            commands = [
                ['git', 'config', '--global', 'user.name', '"YourName"'],
                ['git', 'config', '--global', 'user.email', '"your@email.com"'],
                ['repo', 'init', '-u', repo_url, '-b', branch, '--no-repo-verify'],
                ['repo', 'sync', '-c', '-j', str(self.config['jobs'])]
            ]
            for cmd in commands:
                if not self._execute_cmd(cmd):
                    sys.exit(1)

    def build_image(self):
        """执行编译流程[1,2,3](@ref)"""
        build_cmd = [
            './build.sh',
            '--product-name', self.config['product'],
            '--target-arch', self.config['target_arch'],
            '--jobs', str(self.config['jobs'])
        ]
        
        # Windows环境特殊处理
        if self.os_type == 'Windows':
            build_cmd.insert(0, 'python')
            
        print("开始编译...")
        if self._execute_cmd(build_cmd):
            print(f"编译成功！输出目录：{self.script_path}/out/{self.config['product']}")
        else:
            print("编译失败，查看日志：", self.log_file)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--product', help='编译产品名称')
    parser.add_argument('--arch', help='目标架构')
    args = parser.parse_args()
    
    builder = OpenHarmonyBuilder({
        'product': args.product or 'rk3568',
        'target_arch': args.arch or 'arm64'
    })
    
    builder.check_dependencies()
    builder.setup_repo()
    builder.build_image()
